#include"DLNode.h"

DLNode* DLNodeApply(DLNDataType x)
{
	DLNode* node = (DLNode*)malloc(sizeof(DLNDataType));
	if (node == NULL)
	{
		perror("malloc failed!");
		exit(1);
	}
	node->data = x;
	node->next = node->prev = node;
	return node;
}

void DLNodePrint(DLNode* phead)
{
	DLNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}

void DLNodeInit(DLNode** pphead)
{
	*pphead = DLNodeApply(-1);
}

void DLNodePushBack(DLNode* phead, DLNDataType x)
{
	assert(phead);
	DLNode* newnode = DLNodeApply(x);
	newnode->next = phead;
	newnode->prev = phead->prev;
	phead->prev->next = newnode;
	phead->prev = newnode;
}

void DLNodePushFront(DLNode* phead, DLNDataType x)
{
	assert(phead);
	DLNode* newnode = DLNodeApply(x);
	newnode->next = phead->next;
	newnode->prev = phead;
	phead->next->prev = newnode;
	phead->next = newnode;
	
}

void DLNodePopBack(DLNode* phead)
{
	assert(phead && phead->next != phead);
	DLNode* del = phead->prev;
	phead->prev->prev->next = phead;
	phead->prev = phead->prev->prev;
	free(del);
	del = NULL;
}

void DLNodePopFront(DLNode* phead)
{
	assert(phead && phead->next != phead);
	DLNode* del = phead->next;
	phead->next = phead->next->next;
	phead->next->next->prev = phead;
	free(del);
	del = NULL;
}

DLNode* DLNodeFind(DLNode* phead, DLNDataType x)
{
	DLNode* find = phead->next;
	while (find != phead)
	{
		if (find->data == x)
			return find;
		find = find->next;
	}
	return NULL;
}